import { app } from '../../scripts/app.js'

// 存储节点与Vue实例的映射关系
const nodeVueInstances = new Map();

// 带命名空间的事件总线，避免冲突
const marvelousEventBus = {
  on: (type, callback) => {
    const eventName = `marvelous:${type}`;
    window.addEventListener(eventName, callback);
  },
  emit: (type, detail) => {
    const eventName = `marvelous:${type}`;
    window.dispatchEvent(new CustomEvent(eventName, { detail }));
  },
  off: (type, callback) => {
    const eventName = `marvelous:${type}`;
    window.removeEventListener(eventName, callback);
  }
};

window.marvelousEventBus = marvelousEventBus;
console.log("事件总线已挂载：window.marvelousEventBus");


app.registerExtension({
    name: "comfy.marvelous_node",
    init() {
        try {
            //this.createVueMount();
            //this.loadResources();
            // 移除全局监听器，改用节点专属监听
            // initGlobalListeners();
            // this.initWebSocket();
        } catch (e) {
            console.error("[init] 初始化错误:", e);
        }
    },
    createVueMount: function () {
        console.log("[createVueMount] 执行");
        if (!document.getElementById('marvelous-vue-root')) {
            const div = document.createElement('div');
            div.id = 'marvelous-vue-root';
            document.body.appendChild(div);
        }
    },
    onNodeRemoved(nodeId) {
        console.log(`[onNodeRemoved] 节点${nodeId}被删除，开始清理Vue资源`);
        const vueResource = nodeVueInstances.get(nodeId);
        if (!vueResource) {
            console.log(`[onNodeRemoved] 节点${nodeId}无关联的Vue资源，无需清理`);
            return;
        }

        // 1. 销毁Vue应用实例
        if (vueResource.app) {
            vueResource.app.unmount();
            console.log(`[onNodeRemoved] 节点${nodeId}的Vue应用已卸载`);
        }

        // 2. 执行自定义清理函数
        if (typeof vueResource.cleanup === 'function') {
            vueResource.cleanup();
            console.log(`[onNodeRemoved] 节点${nodeId}的清理函数已执行`);
        }

        // 3. 移除DOM挂载点
        if (vueResource.mountPoint && vueResource.mountPoint.parentNode) {
            vueResource.mountPoint.parentNode.removeChild(vueResource.mountPoint);
            console.log(`[onNodeRemoved] 节点${nodeId}的Vue挂载点已移除`);
        }

        // 4. 移除事件监听
        if (vueResource.eventCallbacks) {
            Object.entries(vueResource.eventCallbacks).forEach(([type, callback]) => {
                window.marvelousEventBus.off(type, callback);
                console.log(`[onNodeRemoved] 节点${nodeId}的${type}事件监听已移除`);
            });
        }

        // 5. 从映射表中删除记录
        nodeVueInstances.delete(nodeId);
        console.log(`[onNodeRemoved] 节点${nodeId}的Vue资源已完全清理`);
    },
    initWebSocket: function () {
        let socket;
        let reconnectInterval;
        const RECONNECT_DELAY = 5000;

        const connect = () => {
            if (socket) {
                socket.close();
            }

            socket = new WebSocket('ws://localhost:8765');

            socket.addEventListener('open', (event) => {
                socket.send('hello world');
                if (reconnectInterval) {
                    clearInterval(reconnectInterval);
                    reconnectInterval = null;
                }
            });

            socket.addEventListener('message', (event) => {
                try {
                    let message = JSON.parse(event.data);
                    if (message.type == 'PROMPT_UPDATE') {
                        updateNodesByTitle('MarvelousText', 'prompt_text', message.data.prompt);
                    }
                    else if (message.type == 'LORA_UPDATE') {
                        updateNodesByTitle('MarvelousLoraLoader', 'loras_json', message.data.loraJson);
                    }
                    else if (message.type == 'GET_NODE_LIST') {
                        const targetNodes = app.graph._nodes.filter(node => node.title === 'MarvelousText');
                        const nodeInfoList = targetNodes.map(node => ({
                            id: node.id,
                            title: node.title,
                            type: node.type,
                        }));
                        if (socket.readyState === WebSocket.OPEN) {
                            socket.send(JSON.stringify({
                                type: 'NODE_LIST_RESPONSE',
                                data: {
                                    nodeCount: nodeInfoList.length,
                                    nodes: nodeInfoList
                                }
                            }));
                        }
                    }
                } catch (e) {
                    console.error('解析消息失败:', e);
                }
            });

            socket.addEventListener('error', (error) => {
                console.error('连接错误:', error);
            });

            socket.addEventListener('close', (event) => {
                console.log('连接关闭:', event.code, event.reason);
                if (event.code !== 1000 && event.code !== 1001) {
                    console.log(`将在${RECONNECT_DELAY / 1000}秒后尝试重连...`);
                    if (!reconnectInterval) {
                        reconnectInterval = setInterval(connect, RECONNECT_DELAY);
                    }
                }
            });
        };

        connect();

        window.addEventListener('beforeunload', () => {
            if (reconnectInterval) {
                clearInterval(reconnectInterval);
            }
            if (socket) {
                socket.close(1000, '页面关闭');
            }
        });
    },
    loadResources: function () {
        console.log("[loadResources] 开始加载资源");
        const script = document.createElement('script');
        const appPath = "/extensions/Marvelous-Box-Comfyui/javascript/main.entry.js";
        script.src = appPath + `?t=${Date.now()}`;
        script.onload = () => console.log("[Vue资源] 加载成功");
        script.onerror = (e) => console.error("[Vue资源] 加载失败:", e);
        document.head.appendChild(script);
    },
    modifyNodesBeforeExecution() {
        console.log("before created")
        return new Promise((resolve) => {
            const requestEvent = new CustomEvent("marvelous-onprocessed", {});
            window.dispatchEvent(requestEvent);
            setTimeout(resolve, 2000);
        });
    },
    async beforeRegisterNodeDef(nodeType, nodeData) {
        if (nodeData.name === "MarvelousBox") {
            console.log(`[beforeRegisterNodeDef] 处理节点类型: ${nodeData.name}`);
            const self = this;

            const originalOnNodeCreated = nodeType.prototype.onNodeCreated;

            nodeType.prototype.onNodeCreated = function() {
                if (originalOnNodeCreated) {
                    originalOnNodeCreated.apply(this, arguments);
                }

                console.log(`[onNodeCreated] 节点刚创建，临时ID: ${this.id}`);

                // 隐藏prompt_text输入框
                const hidePromptInput = () => {
                    const promptWidget = this.widgets.find(w => w.name === 'prompt_text');
                    if (promptWidget) {
                        promptWidget.computeSize = () => [0, -4];
                        promptWidget.hidden = true;
                    } else {
                        console.warn(`[hidePromptInput] 节点${this.id}未找到prompt_text Widget`);
                    }
                    const loraWidget = this.widgets.find(w => w.name === 'loras_json');
                    if (loraWidget) {
                        loraWidget.computeSize = () => [0, -4];
                        loraWidget.hidden = true;
                    } else {
                        console.warn(`[hidePromptInput] 节点${this.id}未找到loras_json Widget`);
                    }
                };

                hidePromptInput();

                // 创建自定义容器
                let customContainer = document.createElement('div');
                customContainer.style.width = '100%';
                customContainer.style.height = '100%';
                customContainer.style.overflow = 'hidden';
                customContainer.style.padding = '10px';
                customContainer.style.boxSizing = 'border-box';
                customContainer.style.backgroundColor = 'rgba(30, 30, 40, 0.6)';
                customContainer.style.borderRadius = '4px';

                if (!this.widgets?.find(w => w.name === 'custom_vue_container')) {
                    console.log(`[onNodeCreated] 为节点${this.id}添加自定义DOM Widget`);
                    this.addDOMWidget(
                        'custom_vue_container',
                        'custom_data',
                        customContainer,
                        {
                            serialize: false,
                            hideOnZoom: false,
                            getValue: () => null,
                            setValue: (value) => {
                                console.log(`[custom_vue_container] 节点${this.id}设置值:`, value);
                            }
                        }
                    );
                }
                self.mountVueToCustomContainer(this, customContainer);
            };
        }
    },
    // 挂载Vue应用到节点，核心改进逻辑
    mountVueToCustomContainer(node, container) {
        console.log(`[mountVueToCustomContainer] 开始处理节点（临时ID: ${node.id}）`);

        // 加载Vue3库
        const loadVue3 = () => {
            return new Promise((resolve, reject) => {
                if (window.Vue) {
                    console.log("[mountVueToCustomContainer] Vue3已加载，跳过加载步骤");
                    resolve();
                    return;
                }

                console.log("[mountVueToCustomContainer] 开始加载本地Vue3资源");
                const vueScript = document.createElement('script');
                vueScript.src = "/extensions/Marvelous-Box-Comfyui/javascript/vue.global.min.js?" + Date.now();

                vueScript.onload = () => {
                    console.log("[mountVueToCustomContainer] 本地Vue3加载成功");
                    resolve();
                };
                vueScript.onerror = (e) => {
                    console.error("[mountVueToCustomContainer] 本地Vue3加载失败:", e);
                    reject(new Error("本地Vue3文件加载失败，请检查文件路径是否正确"));
                };
                document.head.appendChild(vueScript);
            });
        };

        // 加载自定义Vue应用
        const loadCustomVueApp = () => {
            return new Promise((resolve, reject) => {
                if (window.mountMarvelousVueApp) {
                    console.log("[mountVueToCustomContainer] 自定义Vue应用已加载");
                    resolve();
                    return;
                }

                console.log("[mountVueToCustomContainer] 开始加载自定义Vue应用");
                const appScript = document.createElement('script');
                const appPath = "/extensions/Marvelous-Box-Comfyui/javascript/main.entry.js";
                appScript.src = appPath + `?t=${Date.now()}`;

                appScript.onload = () => {
                    console.log("[mountVueToCustomContainer] 自定义Vue应用加载成功");
                    resolve();
                };
                appScript.onerror = (e) => {
                    console.error("[mountVueToCustomContainer] 自定义Vue应用加载失败:", e);
                    reject(e);
                };
                document.head.appendChild(appScript);
            });
        };

        // 异步加载并挂载Vue应用（关键改进：延迟创建挂载点）
        loadVue3()
            .then(loadCustomVueApp)
            .then(() => {
                // 此时node.id已为最终有效ID（非-1）
                console.log(`[mountVueToCustomContainer] 异步加载完成，节点最终ID: ${node.id}`);

                const containerId = `vue-custom-container-${this.id}`;
                const vueMountPoint = document.createElement('div');
                vueMountPoint.id = `marvelous-vue-root-${node.id}`;
                vueMountPoint.style.width = '100%';
                vueMountPoint.style.height = '100%';
                vueMountPoint.style.position = 'relative';
                container.appendChild(vueMountPoint);
                container.id = containerId
                if (window.mountMarvelousVueApp) {
                    console.log(`[mountVueToCustomContainer] 开始挂载Vue3应用到节点${node.id}`);
                    console.log(containerId)
                    // 挂载Vue应用
                    const vueApp = window.mountMarvelousVueApp(vueMountPoint, {
                        nodeId: node.id,
                        nodeData: node.data
                    });

                    // 注册节点专属事件回调
                    const nodeId = node.id;
                    const handleUpdateText = (e) => {
                        if (e.detail.nodeId === nodeId) {
                            updateNodeParam(nodeId, 'prompt_text', e.detail.text);
                        }
                    };
                    const handleUpdateLora = (e) => {
                        if (e.detail.nodeId === nodeId) {
                            updateNodeParam(nodeId, 'loras_json', e.detail.text);
                        }
                    };

                    // 注册事件监听
                    window.marvelousEventBus.on('update-text', handleUpdateText);
                    window.marvelousEventBus.on('update-lora', handleUpdateLora);
                    // 存储所有资源到映射表
                    nodeVueInstances.set(nodeId, {
                        app: vueApp.instance,
                        cleanup: vueApp.cleanup,
                        mountPoint: vueMountPoint,
                        eventCallbacks: { 'update-text': handleUpdateText,'update_lora': handleUpdateLora}
                    });
                    node.vueMountPoint = vueMountPoint;
                    console.log(`[mountVueToCustomContainer] 节点${node.id} Vue3应用挂载完成，挂载点ID: ${vueMountPoint.id}`);
                } else {
                    console.error("[mountVueToCustomContainer] 未找到window.mountMarvelousVueApp方法，请检查Vue项目打包配置");
                }
            })
            .catch((error) => {
                console.error("[mountVueToCustomContainer] 加载流程出错:", error);
                // 创建错误提示容器
                const errorMountPoint = document.createElement('div');
                errorMountPoint.id = `marvelous-vue-error-${node.id}`;
                errorMountPoint.innerHTML = `
                    <div style="color: red; padding: 10px; text-align: center;">
                        应用加载失败: ${error.message}<br>
                        请刷新页面重试
                    </div>
                `;
                container.appendChild(errorMountPoint);
            });
    }
});

// 更新节点参数的工具函数
function updateNodeParam(nodeId, paramName, value) {
    const node = app.graph._nodes_by_id[nodeId]
    if (node) {
        const textWidget = node.widgets.find(w => w.name === paramName);
        if (textWidget) {
            textWidget.value = value;
            node.onWidgetChange?.(textWidget);
            app.graph.setDirtyCanvas(); // 修复：添加括号确保执行刷新
            console.log(`[updateNodeParam] 节点${nodeId}的${paramName}已更新为:`, value);
        } else {
            console.warn(`[updateNodeParam] 节点${nodeId}未找到参数${paramName}`);
        }
    } else {
        console.warn(`[updateNodeParam] 未找到ID为${nodeId}的节点`);
    }
}

function updateNodesByTitle(title, paramName, value) {
    const node = app.graph._nodes.find(w => w.title == title)
    if (node) {
        const textWidget = node.widgets.find(w => w.name === paramName);
        if (textWidget) {
            textWidget.value = value;
            node.onWidgetChange?.(textWidget);
            app.graph.setDirtyCanvas();
        }
    }
}
